package com.lc.luzhengtang.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.activity.ConfirmOrderActivity;
import com.lc.luzhengtang.adapter.ShopCarAdapter;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.bean.ShopCarListBean;
import com.lc.luzhengtang.conn.ConnDeleteShopCar;
import com.lc.luzhengtang.conn.ConnShopCar;
import com.lc.luzhengtang.divider.SimpleDividerItemDecoration;
import com.lc.luzhengtang.util.LovelyToast;
import com.zcx.helper.http.AsyCallBack;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/5/2.
 */

public class ShoppingFragment extends BaseFragment3 implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.iv_search)
    TextView ivSearch;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.rl_refresh)
    SwipeRefreshLayout rlRefresh;

    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.bt_balance)
    Button btBalance;
    @BindView(R.id.rl_all_check)
    RelativeLayout rlAllCheck;
    Unbinder unbinder;
    /*
        List<String> mDatas;
        List<String> mDatas2;*/
    ShopCarAdapter shopCarAdapter;
    private int mCurrentCounter = 0;
    private boolean isErr;
    private boolean mLoadMoreEndGone = false;
    private double total = 0.00;

    private static final int TOTAL_COUNTER = 18;

    private static final int PAGE_SIZE = 6;


    List<ShopCarListBean.DataBeanX.DataBean> dataBeen;

    CheckBox checkBox;

    private int cart_id;
    private String cart_ids;

    private String format = "" + 0.00;
    public boolean isShowBack = false;
    private boolean isAllChecked;
    private TextView mClear;
    private int currentPage = 1;
    List<ShopCarListBean.DataBeanX.DataBean> results;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_shopcar, null);
        unbinder = ButterKnife.bind(this, view);
        dataBeen = new ArrayList<>();
        rlRefresh.setOnRefreshListener(this);
        rlRefresh.setColorSchemeColors(Color.rgb(47, 223, 189));

        checkBox = (CheckBox) view.findViewById(R.id.scb);
        checkBox.setChecked(false);
        initData();
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isAllChecked = !isAllChecked;
                    checkBox.setChecked(isAllChecked);
                  /*  for (int i = 0; i < dataBeen.size(); i++) {
                        dataBeen.get(i).setChoose(true);
                    }*/
                    shopCarAdapter.listener.startCalculate();
                    shopCarAdapter.notifyDataSetChanged();


                }else {
                    isAllChecked = !isAllChecked;
                    checkBox.setChecked(isAllChecked);
                    for (int i = 0; i < dataBeen.size(); i++) {
                       // dataBeen.get(i).setChoose(false);
                    }
                    shopCarAdapter.listener.startCalculate();
                    shopCarAdapter.notifyDataSetChanged();
                }
            }
        });

        return view;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    protected void initData() {
        rvList.setItemAnimator(new DefaultItemAnimator());
        //recyclerView.setLayoutManager(new LinearLayoutManager(context));
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));

        shopCarAdapter = new ShopCarAdapter(null);
        shopCarAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        shopCarAdapter.isFirstOnly(false);
        Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.line_divider);
        rvList.addItemDecoration(new SimpleDividerItemDecoration(getActivity(), drawable, 1));

        rvList.setAdapter(shopCarAdapter);


        shopCarAdapter.setListener(new ShopCarAdapter.Listener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void startCalculate() {
                total = 0;
                format = new DecimalFormat("#.00").format(total);
                for (int i = 0; i < dataBeen.size(); i++) {
                    if (dataBeen.get(i).getSelected()) {
                        Double money = dataBeen.get(i).getNumber() * Double.parseDouble(dataBeen.get(i).getMarket_price());
                        total += money;
                        format = new DecimalFormat("#.00").format(total);
                    }
                }
                if (total == 0) {
                    tvTotalPrice.setText("￥ 0.0");
                } else {
                    if (format != null) {
                        tvTotalPrice.setText("￥ " + format);
                    } else {
                        tvTotalPrice.setText("￥ 0.0");
                    }
                }
            }
            @Override
            public void checkAll(int position, boolean isCChecked) {
                if (isAllCheck()) {// 全选
                    if (!checkBox.isChecked()) {
                        checkBox.setChecked(isCChecked);
                        shopCarAdapter.notifyDataSetChanged();
                        isAllChecked = true;
                    }

                } else {
                    Log.i("b", position + "");
                    if (checkBox.isChecked()) {
                        checkBox.setChecked(isCChecked);
                        shopCarAdapter.notifyDataSetChanged();
                        isAllChecked = false;
                    }
                }

            }

        });


        rlRefresh.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        rlRefresh.setOnRefreshListener(this);
        shopCarAdapter.setOnLoadMoreListener(this);

        //开启loading,获取数据
        setRefreshing(true);
        onRefresh();
    }

    public void setRefreshing(final boolean refreshing) {
        rlRefresh.post(new Runnable() {
            @Override
            public void run() {
                rlRefresh.setRefreshing(refreshing);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_search, R.id.scb, R.id.tv_total_price, R.id.bt_balance, R.id.rl_all_check})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_search:
                break;
            case R.id.scb:
                break;
            case R.id.tv_total_price:
                break;
            case R.id.bt_balance:
                // generateOrder();
                payOrder();
                break;
            case R.id.rl_all_check:
                break;
        }
    }

    @Override
    public void onRefresh() {
        checkBox.setChecked(false);
        new ConnShopCar(BaseApplication.basePreferences.readUid(), "1", new AsyCallBack<ShopCarListBean>()

        {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
//                showLoading();
            }

            @Override
            public void onSuccess(String toast, int type, Object o, ShopCarListBean s) throws Exception {
                super.onSuccess(toast, type, o, s);
                dataBeen = s.getData().getData();

                results = s.getData().getData();
                if (results != null) {
                    results.clear();
                    results = s.getData().getData();
                    currentPage = 1;
                    shopCarAdapter.setNewData(results);
                }


                //    pullToRefreshAdapter.setAutoLoadMoreSize(3);

                shopCarAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

                    @Override
                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                        // Toast.makeText(getActivity(), "删除了" + position + "", Toast.LENGTH_SHORT).show();


                        new ConnDeleteShopCar(BaseApplication.basePreferences.readUid(), dataBeen.get(position).getId() + "", new AsyCallBack<CommenBean>() {
                            @Override
                            public void onStart(int type) throws Exception {
                                super.onStart(type);
                            }

                            @Override
                            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                                super.onSuccess(toast, type, o, commenBean);
                                Toast.makeText(getActivity(), commenBean.getMessage(), Toast.LENGTH_SHORT).show();
                                //     getData();
                                onRefresh();
                            }


                            @Override
                            public void onFail(String toast, int type) throws Exception {
                                super.onFail(toast, type);
                            }

                            @Override
                            public void onEnd(String toast, int type) throws Exception {
                                super.onEnd(toast, type);
                            }
                        }


                        ).execute(getActivity(), false);


                    }
                });



                /*  dataBeen.clear();
                dataBeen.addAll(s.getData().getData());
                shopCarAdapter = new ShopCarAdapter(R.layout.item_shoppingcar, dataBeen);

                // pullToRefreshAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
//        shopCarAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
//        pullToRefreshAdapter.setAutoLoadMoreSize(3);
                rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
                rvList.setAdapter(shopCarAdapter);
                shopCarAdapter.notifyDataSetChanged();
                shopCarAdapter.setListener(new ShopCarAdapter.Listener() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void startCalculate() {
                        total = 0;
                        format = new DecimalFormat("#.00").format(total);
                        for (int i = 0; i < dataBeen.size(); i++) {
                            if (dataBeen.get(i).getSelected()) {
                                Double money = dataBeen.get(i).getNumber() * Double.parseDouble(dataBeen.get(i).getMarket_price());
                                total += money;
                                format = new DecimalFormat("#.00").format(total);
                            }
                        }
                        if (total == 0) {
                            tvTotalPrice.setText("￥ 0.0");
                        } else {
                            if (format != null) {
                                tvTotalPrice.setText("￥ " + format);
                            } else {
                                tvTotalPrice.setText("￥ 0.0");
                            }
                        }
                    }

                    @Override
                    public void checkAll(int position, boolean isCChecked) {
                        if (isAllCheck()) {// 全选
                            if (!checkBox.isChecked()) {
                                checkBox.setChecked(isCChecked);
                                shopCarAdapter.notifyDataSetChanged();
                                isAllChecked = true;
                            }

                        } else {
                            Log.i("b", position + "");
                            if (checkBox.isChecked()) {
                                checkBox.setChecked(isCChecked);
                                shopCarAdapter.notifyDataSetChanged();
                                isAllChecked = false;
                            }
                        }

                    }

                });


                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        for (int i = 0; i < dataBeen.size(); i++) {
                            dataBeen.get(i).setSelected(isChecked);
                        }
                        shopCarAdapter.notifyDataSetChanged();
                        shopCarAdapter.listener.startCalculate();
                    }
                });



*/

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
//                dismissLoading();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                //                newsAdapter.removeAllFooterView();
                //最后调用结束刷新的方法
//                dismissLoading();
                setRefreshing(false);
                shopCarAdapter.setEnableLoadMore(false);
            }
        }

        ).execute(getActivity(), false);
    }

    @Override
    public void onLoadMoreRequested() {
        checkBox.setChecked(false);
        new ConnShopCar(BaseApplication.basePreferences.readUid(), "1", new AsyCallBack<ShopCarListBean>()

        {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, ShopCarListBean s) throws Exception {
                super.onSuccess(toast, type, o, s);
                // dataBeen = s.getData().getData();
                results = s.getData().getData();
                if (results != null && results.size() > 0) {
                    currentPage++;
                    shopCarAdapter.setNewData(results);
                } else {
                    shopCarAdapter.loadMoreComplete();
                    View noDataView = LayoutInflater.from(getActivity()).inflate(R.layout.item_no_data, (ViewGroup) rvList.getParent(), false);
                    shopCarAdapter.addFooterView(noDataView);
                }

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                //                newsAdapter.removeAllFooterView();
                //最后调用结束刷新的方法
                setRefreshing(false);
                shopCarAdapter.setEnableLoadMore(false);
            }
        }

        ).execute(getActivity(), false);
    }


    private boolean istrue = true;
    private String id;


    //结算
    private void payOrder() {

        istrue = false;
        StringBuilder sb = new StringBuilder();
        for (int r = 0; r < dataBeen.size(); r++) {

           /* if (dataBeen.get(r).isChoose()) {

                sb.append(dataBeen.get(r).getId());

                sb.append(",");
            }*/
        }

        if (sb.length()<1){
            LovelyToast.makeText(getActivity(), "请选择商品", 0, LovelyToast
                    .SUCCESS, LovelyToast.SCALE);
        }


        sb.deleteCharAt(sb.length() - 1);
        id = sb.toString();

        Intent intent = new Intent();

        intent.putExtra("cart_id", id);

        intent.setClass(getActivity(), ConfirmOrderActivity.class);
        startActivity(intent);

//        Bundle bundle = new Bundle();
//        bundle.putString("id", id);
//        bundle.putString("title", "购物车");
//        bundle.putString("mTitle", "购物车");
//        startActivity(new Intent(getContext(), ConfirmOrderActivity.class).putExtras(bundle));
     /*   cart_ids = "";
        for (int i = 0; i < dataBeen.size(); i++) {
            cart_id = dataBeen.get(i).getGoods_id();
            cart_ids += "," + cart_id;
        }





        Bundle bundle = new Bundle();
        bundle.putInt("type", 1);
        bundle.putString("cart_id", cart_ids.replaceFirst(",", ""));
        Intent intent = new Intent();

//        intent.putExtra("cart_id",cart_ids.replaceFirst(",",""));
//        intent.putExtra("cart_id",cart_ids);
//        intent.setClass(getActivity(),ConfirmOrderActivity.class);
//
//        startActivity(intent);

        startVerifyActivity(ConfirmOrderActivity.class, new Intent().putExtras(bundle));*/
    }


    /**
     *
     */
    private boolean isAllCheck() {
        for (ShopCarListBean.DataBeanX.DataBean grup : dataBeen) {
            if (!grup.getSelected()) {
                return false;
            }
        }
        return true;
    }


}
